package com.lemon.smartsafety.ui.activity.bind;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TableLayout;
import android.widget.TableRow;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.lemon.android.http.Field;
import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.BundleKey;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.app.EventTag;
import com.lemon.smartsafety.entity.bind.GovInfoVo;
import com.lemon.smartsafety.entity.common.AreaVo;
import com.lemon.smartsafety.entity.common.SelectDataI;
import com.lemon.smartsafety.entity.event.common.AreaSelectEvent;
import com.lemon.smartsafety.entity.event.common.MultiSelectItemEvent;
import com.lemon.smartsafety.entity.event.common.SelectItemEvent;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafety.http.service.BindInfoServices;
import com.lemon.smartsafety.listener.AreaType;
import com.lemon.smartsafetynew.ui.activity.base.SwipeBackActivity;
import com.lemon.smartsafety.ui.activity.common.AreaProvinceActivity;
import com.lemon.smartsafety.ui.activity.common.IndustryActivity;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.DateUtils;
import com.lemon.smartsafety.utils.common.LoggerHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafety.view.tagview.OnTagDeleteListener;
import com.lemon.smartsafety.view.tagview.Tag;
import com.lemon.smartsafety.view.tagview.TagView;
import com.rengwuxian.materialedittext.MaterialEditText;

import org.greenrobot.eventbus.Subscribe;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by Cooliean on 16/4/9.
 */
public class GovPropInfoActivity extends SwipeBackActivity {

    private LoggerHelper loggerHelper = new LoggerHelper(GovPropInfoActivity.class);


    @Bind(R.id.tl_basic_info)
    TableLayout      tlBasicInfo;
    @Bind(R.id.metGovName)
    MaterialEditText metGovName;
    @Bind(R.id.metGovCode)
    MaterialEditText metGovCode;
    @Bind(R.id.metRespPerson)
    MaterialEditText metRespPerson;
    @Bind(R.id.metRespPhone)
    MaterialEditText metRespPhone;
    @Bind(R.id.metArea)
    MaterialEditText metArea;
    @Bind(R.id.rowArea)
    TableRow         rowArea;


    @Bind(R.id.tagIndustryBranch)
    TagView  tagIndustryBranch;
    @Bind(R.id.rowIndustryBranch)
    TableRow rowIndustryBranch;

    @Bind(R.id.metIndustryMaster)
    MaterialEditText metIndustryMaster;
    @Bind(R.id.rowIndustryMaster)
    TableRow         rowIndustryMaster;
    @Bind(R.id.btn_submit)
    Button           btnSubmit;
    @Bind(R.id.tr_button)
    TableRow         trButton;


    @Bind(R.id.arrowArea)
    ImageView arrowArea;


    @Bind(R.id.arrowIndustryBranch)
    ImageView arrowIndustryBranch;

    @Bind(R.id.arrowIndustryMaster)
    ImageView arrowIndustryMaster;

    /**
     * 不能修改
     */
    private boolean bCantEdit        = false;
    private String  mApplicationCode = null;

    private GovInfoVo mGovInfoVo;
    private List<SelectDataI> selectIndustryBranch = new ArrayList<>();
    private SelectDataI mIndustryMaster;

    private SelectDataI mAreaProvince, mAreaCity, mAreaDistrict, mAreaStreet, mAreaVillage;


    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();
        if (getIntent().getExtras() != null) {
            mApplicationCode = getIntent().getStringExtra(BundleKey.APPLICATION_CODE);
            bCantEdit = getIntent().getBooleanExtra(BundleKey.CANT_EDIT, false);
            mGovInfoVo = (GovInfoVo) getIntent().getSerializableExtra(BundleKey.GOV_INFO);
        }
        mApplicationCode = StringUtils.nullValue(mApplicationCode);
    }


    @Override
    protected void initTitle() {
        setBarTitle("机构信息");
    }

    @Override
    protected void callFinish() {
        AppManager.getAppManager().finishActivity(GovPropInfoActivity.this);
    }


    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            callFinish();
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected int getContentViewId() {
        return R.layout.activity_bind_gov_prop;
    }

    @Override
    protected void initViews() {
        super.initViews();

        metIndustryMaster.setTag("");

        if (bCantEdit && null == mGovInfoVo) {
            mHUDUtil.showErrorTip(getString(R.string.params_error), new HUDUtil.CallBack() {
                @Override
                public void onCall() {
                    callFinish();
                }
            });
        }


        if (!bCantEdit) {
            tagIndustryBranch.setOnTagDeleteListener(new OnTagDeleteListener() {
                @Override
                public void onTagDeleted(Tag tag, int position) {
                    selectIndustryBranch.remove(position);
                }
            });

        }
        /**
         * 这里选择过来的
         */
        if (bCantEdit && null != mGovInfoVo) {
            initGovInfoView(mGovInfoVo);
        } else {
            arrowArea.setVisibility(View.VISIBLE);
            arrowIndustryBranch.setVisibility(View.VISIBLE);
            arrowIndustryMaster.setVisibility(View.VISIBLE);
        }
    }

    private void initGovInfoView(GovInfoVo govInfoVo) {
        //loggerHelper.json(govInfoVo);

        metGovName.setText(StringUtils.nullValue(govInfoVo.getGov_name()));
        metGovCode.setText(StringUtils.nullValue(govInfoVo.getGov_code()));
        metRespPerson.setText(StringUtils.nullValue(govInfoVo.getPrincipal_name()));
        metRespPhone.setText(StringUtils.nullValue(govInfoVo.getPrincipal_phone()));
        metArea.setText(getAreaText(govInfoVo));


        selectIndustryBranch.addAll(govInfoVo.getIndustryBranch());
        setTagView(tagIndustryBranch, selectIndustryBranch, R.color.colorAppGreen, !bCantEdit);

        metIndustryMaster.setText(StringUtils.nullValue(govInfoVo.getMain_industry_name()));
        metIndustryMaster.setTag(StringUtils.nullValue(govInfoVo.getMain_industry_id()));


        arrowArea.setVisibility(View.GONE);
        arrowIndustryBranch.setVisibility(View.GONE);
        arrowIndustryMaster.setVisibility(View.GONE);


        disableFormWithOutButton(tlBasicInfo);
    }

    private String getAreaText(GovInfoVo govInfoVo) {
        StringBuilder sb    = new StringBuilder();
        String        title = StringUtils.nullValue(govInfoVo.getPlace_name_province());
        if (title.length() != 0) {
            sb.append(title);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_province_id()));
            mAreaProvince = vo;
        }

        String title2 = StringUtils.nullValue(govInfoVo.getPlace_name_city());
        if (title2.length() != 0) {
            sb.append("-" + title2);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title2);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_city_id()));
            mAreaCity = vo;
        }else{
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        String title3 = StringUtils.nullValue(govInfoVo.getPlace_name_district());
        if (title3.length() != 0) {
            sb.append("-" + title3);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title3);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_district_id()));
            mAreaDistrict = vo;
        }else{
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }
        String title4 = StringUtils.nullValue(govInfoVo.getPlace_name_streets());
        if (title4.length() != 0) {
            sb.append("-" + title4);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title4);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_streets_id()));
            mAreaStreet = vo;
        }else{
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        String title5 = StringUtils.nullValue(govInfoVo.getPlace_name_village());
        if (title5.length() != 0) {
            sb.append("-" + title5);
            AreaVo vo = new AreaVo();
            vo.setSelectedI(true);
            vo.setTitle(title5);
            vo.setVoId(StringUtils.nullValue(govInfoVo.getPosition_village_id()));
            mAreaVillage = vo;
        }else{
            mAreaVillage = null;
        }
        return sb.toString();
    }


    @OnClick({R.id.btn_submit})
    public void submitAction(View view) {
        if (!validateForm()) {
            return;
        }
        getConfirmDialog("是否绑定？", new MaterialDialog.SingleButtonCallback() {
            @Override
            public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                if (which == DialogAction.POSITIVE) {
                    if (!bCantEdit) {
                        doSubmitAction();
                    } else {
                        bindInfoAction();
                    }
                }
            }
        }).show();

    }

    /**
     * 保存新的机构信息
     */
    private void doSubmitAction() {
        final LemonRequestParams params = new LemonRequestParams("gov_info", "gov_id", "");

        params.put("_txtIdValues", "");
        params.put("gov_id", "");
        params.put("application_code", mApplicationCode);
        params.put("user_id", mSharedPreferencesHelper.getUserId());
        params.put("txtGovName", metGovName.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtGovCode", metGovCode.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtRecordDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATE);
        params.put("txtLastModifyDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATE);
        params.put("txtRecorderId", mSharedPreferencesHelper.getUserId(), Field.TYPE_STRING);
        params.put("txtPrincipalName", metRespPerson.getText().toString().trim(), Field.TYPE_STRING);
        params.put("txtPrincipalPhone", metRespPhone.getText().toString().trim(), Field.TYPE_STRING);


        if (mAreaProvince != null) {
            params.put("selPositionProvinceId", mAreaProvince.getValue(), Field.TYPE_STRING);
        }
        if (mAreaCity != null) {
            params.put("selPositionCityId", mAreaCity.getValue(), Field.TYPE_STRING);
        }
        if (mAreaDistrict != null) {
            params.put("selPositionDistrictId", mAreaDistrict.getValue(), Field.TYPE_STRING);
        }
        if (mAreaStreet != null) {
            params.put("selPositionStreetsId", mAreaStreet.getValue(), Field.TYPE_STRING);
        }
        if (mAreaVillage != null) {
            params.put("selPositionVillageId", mAreaVillage.getValue(), Field.TYPE_STRING);
        }

        params.put("selIndustryTypeIds", getListSplit(selectIndustryBranch), Field.TYPE_STRING);


        params.put("txtIndustryTypeId", metIndustryMaster.getTag().toString(), Field.TYPE_INT);


        BindInfoServices.init().saveGovInfoAction(params, false);

    }

    /**
     * 绑定现有的机构
     */
    private void bindInfoAction() {
        final LemonRequestParams params = new LemonRequestParams("application_user_bind", "bind_id", "");

        params.put("_txtIdValues", "");
        params.put("bind_id", "");
        params.put("user_id", mSharedPreferencesHelper.getUserId());
        params.put("txtApplicationCode", mApplicationCode, Field.TYPE_STRING);
        params.put("txtUserId", mSharedPreferencesHelper.getUserId(), Field.TYPE_STRING);
        params.put("txtBindDate", DateUtils.getCurrentYMDHMSDate(), Field.TYPE_DATETIME);
        params.put("txtStatus", "0", Field.TYPE_INT);
        params.put("txtBindType", "gov", Field.TYPE_STRING);
        params.put("txtBindCode", metGovCode.getText().toString().trim(), Field.TYPE_STRING);

        BindInfoServices.init().saveApplicationInfo(params);
    }

    private boolean validateForm() {
        if (bCantEdit) {//若果是选择的机构直接就不检验表单了
            return true;
        }
        if (TextUtils.isEmpty(metGovName.getText().toString().trim())) {
            metGovName.setError("请填写机构名称");
            mHUDUtil.showErrorTip(metGovName.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metGovCode.getText().toString().trim())) {
            metGovCode.setError("请填写机构代码");
            mHUDUtil.showErrorTip(metGovCode.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metRespPerson.getText().toString().trim())) {
            metRespPerson.setError("请填写机构负责人");
            mHUDUtil.showErrorTip(metRespPerson.getError().toString());
            return false;
        }

        if (TextUtils.isEmpty(metRespPhone.getText().toString().trim())) {
            metRespPhone.setError("请填写机构负责人电话");
            mHUDUtil.showErrorTip(metRespPhone.getError().toString());
            return false;
        }


        if (TextUtils.isEmpty(metArea.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择管辖地区");
            return false;
        }


        if (selectIndustryBranch.isEmpty()) {
            mHUDUtil.showErrorTip("请选择分管行业");
            return false;
        }


        if (TextUtils.isEmpty(metIndustryMaster.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请选择主管行业");
            return false;
        }
        return true;
    }


    /**
     * http处理请求的处理
     *
     * @param event
     */
    @Subscribe
    public void onEventMainThread(HttpCallbackEvent event) {
        if (EventTag.TAG_BIND_SAVE_ACTION.equals(event.getTag())) {
            if (event.getHttpFlow() == HandlerCallback.HttpFlow.START) {
                mHUDUtil.showHUD();
            } else if (event.getHttpFlow() == HandlerCallback.HttpFlow.FINISH) {
                if (event.getEventResult() == Constants.Result.SUCCESS) {
                    mHUDUtil.showDoneTip(event.getMsg(), new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            AppManager.getAppManager().finishActivity(GovPropInfoActivity.class);
                            AppManager.getAppManager().finishActivity(BindGovListActivity.class);
                        }
                    });
                } else {
                    mHUDUtil.showErrorTip(event.getMsg());
                }
            }
        }
    }


    @OnClick({R.id.metArea, R.id.rowArea, R.id.rowIndustryBranch, R.id.rowIndustryMaster, R.id.metIndustryMaster})
    public void onClick(View view) {
        if (view.getId() == R.id.metArea || view.getId() == R.id.rowArea) {//地域选择
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_FOR_REGISTER, false);
            UIHelper.showActivity(GovPropInfoActivity.this, bundle, AreaProvinceActivity.class);
        } else if (view.getId() == R.id.rowIndustryBranch) {//分管行业
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_MULTI_SELECT, true);
            bundle.putSerializable(BundleKey.OLD_SELECT_VALUE_LIST, (Serializable) selectIndustryBranch);
            UIHelper.showActivity(this, bundle, IndustryActivity.class);

        } else if (view.getId() == R.id.rowIndustryMaster || view.getId() == R.id.metIndustryMaster) {//主管行业
            Bundle bundle = new Bundle();
            bundle.putBoolean(BundleKey.IS_MULTI_SELECT, false);
            if (mIndustryMaster != null && StringUtils.nullValue(mIndustryMaster.getValue()).length() != 0) {
                bundle.putString(BundleKey.OLD_SELECT_VALUE, mIndustryMaster.getValue());
            }
            UIHelper.showActivity(this, bundle, IndustryActivity.class);
        }
    }


    @Subscribe
    public void onEventMainThread(AreaSelectEvent event) {
        if (AreaType.PROVINCE == event.getType()) {
            mAreaProvince = event.getData();
        } else if (AreaType.CITY == event.getType()) {
            mAreaCity = event.getData();
        } else if (AreaType.DISTRICT == event.getType()) {
            mAreaDistrict = event.getData();
        } else if (AreaType.STREET == event.getType()) {
            mAreaStreet = event.getData();
        } else if (AreaType.VILLAGE == event.getType()) {
            mAreaVillage = event.getData();
        }
        loggerHelper.w(getAreaViewValue());
        metArea.setText(getAreaViewValue());
    }

    private String getAreaViewValue() {
        StringBuilder sb = new StringBuilder();
        if (mAreaProvince != null) {
            String title        = StringUtils.nullValue(mAreaProvince.getTitle());
            sb.append(title);
        }else{
            return sb.toString();
        }
        if (mAreaCity != null) {
            String title        = StringUtils.nullValue(mAreaCity.getTitle());
            sb.append("-" + title);
        }else{
            mAreaCity = null;
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }

        if (mAreaDistrict != null) {
            String title        = StringUtils.nullValue(mAreaDistrict.getTitle());
            sb.append("-" + title);
        }else{
            mAreaDistrict = null;
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaStreet != null) {
            String title        = StringUtils.nullValue(mAreaStreet.getTitle());
            sb.append("-" + title);
        }else{
            mAreaStreet = null;
            mAreaVillage = null;
            return sb.toString();
        }


        if (mAreaVillage != null) {
            String title        = StringUtils.nullValue(mAreaVillage.getTitle());
            sb.append("-" + title);
        }else{
            mAreaVillage = null;
        }

        return sb.toString();
    }




    @Subscribe
    public void onEventMainThread(MultiSelectItemEvent event) {
        List<SelectDataI> items = event.getData();
        if (event.getTag().equals(EventTag.TAG_INDUSTRY)) {
            if (items != null && items.size() != 0) {
                selectIndustryBranch.clear();
                selectIndustryBranch.addAll(items);
                setTagView(tagIndustryBranch, selectIndustryBranch, R.color.colorPrimary, !bCantEdit);
            } else {
                selectIndustryBranch.clear();
                tagIndustryBranch.removeAllTags();
            }
        }
    }


    @Subscribe
    public void onEventMainThread(SelectItemEvent event) {
        if (event.getTag().equals(EventTag.TAG_INDUSTRY)) {
            mIndustryMaster = event.getData();
            metIndustryMaster.setText(mIndustryMaster.getTitle());
            metIndustryMaster.setTag(StringUtils.nullValue(mIndustryMaster.getValue()));
        }
    }


}
